import subprocess
from tool.FileManager import FileManager
import sys


class BuildVue:

    def __init__(self, vue_root, build_cmd):
        self.vueRoot = vue_root
        self.buildCmd = build_cmd

    def main(self):
        print("开始在" + self.vueRoot + "目录下执行命令 :")
        print(self.buildCmd)
        child = subprocess.Popen(self.buildCmd, shell=True, stderr=subprocess.STDOUT, cwd=self.vueRoot)
        # stdout=subprocess.PIPE,  stdin=subprocess.PIPE,管道参数
        child.wait()
        # print("执行结果:")
        # for line in child.stdout.readlines():
        #     output = line.decode('cp936')
        #     print("%s" % output)


def menu(choose_arr):
    print("#########################菜单#########################")
    for cho in choose_arr:
        print(str(choose_arr.index(cho) + 1) + "." + cho["name"])
    print("#########################菜单#########################")
    try:
        choose_index = int(input("请选择:")) - 1
        if int(choose_index) < 0 or choose_index > len(choose_arr):
            print("错误的选择")
            menu(choose_arr)

        vue_root = choose_arr[choose_index]["dir"]
        build_cmd = choose_arr[choose_index]["cmd"]
        bulid_portal = BuildVue(vue_root, build_cmd)
        bulid_portal.main()
    except Exception as e:
        print("异常:" + str(e))
    finally:
        menu(choose_arr)


if __name__ == "__main__":
    file_manager = FileManager('', 'cmd.config')
    if not file_manager.file_is_exists():
        confArr = file_manager.read_conf()
        chooseArr = []

        for line in confArr:
            choose = dict()
            line_cmd = line.split(',')
            if len(line_cmd) != 3:
                print("配置文件格式不标准!")
                break
            choose["name"] = line_cmd[0].split("name:")[1]
            choose["dir"] = line_cmd[1].split("dir:")[1]
            choose["cmd"] = line_cmd[2].split("cmd:")[1]
            chooseArr.append(choose)
        if len(chooseArr) > 0:
            menu(chooseArr)
        else:
            print("没有可选项请检查配置文件!")
            sys.stdin.readline()
    else:
        print("请先配置文件!")
